import React, {createContext, ReactNode, useContext, useEffect, useState} from 'react';
import {ConfigProvider, theme as antdTheme} from 'antd';
import {ThemeType} from "./types";

// 获取实际主题
export const getEffectiveTheme = (theme: ThemeType): ThemeType => {
  return theme === ThemeType.SYSTEM ? getSystemTheme() : theme;
};

// 获取当前系统主题偏好
export const getSystemTheme = (): ThemeType => {
  if (typeof window !== 'undefined' && window.matchMedia) {
    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? ThemeType.DARK
      : ThemeType.LIGHT;
  }
  return ThemeType.LIGHT;
};

// 主题上下文类型
interface ThemeContextType {
  currentTheme: ThemeType;
  setTheme: (theme: ThemeType) => void;
  isDarkMode: boolean;
}

// 创建默认主题上下文值
const defaultThemeContextValue: ThemeContextType = {
  currentTheme: ThemeType.LIGHT,
  setTheme: () => {
  },
  isDarkMode: false,
};

// 创建主题上下文
export const ThemeContext = createContext<ThemeContextType>(defaultThemeContextValue);

// 主题提供者组件的属性类型
interface ThemeProviderProps {
  children: ReactNode;
  defaultTheme?: ThemeType;
}

// 主题提供者组件
export const ThemeProvider: React.FC<ThemeProviderProps> = ({
                                                              children,
                                                              defaultTheme = ThemeType.LIGHT
                                                            }) => {
  // 从本地存储中获取用户之前选择的主题，或使用默认主题
  const [currentTheme, setCurrentTheme] = useState<ThemeType>(() => {
    const savedTheme = localStorage.getItem('app-theme');
    return (savedTheme as ThemeType) || defaultTheme;
  });

  // 追踪是否为暗色模式
  const [isDarkMode, setIsDarkMode] = useState<boolean>(() => {
    const effectiveTheme = getEffectiveTheme(currentTheme);
    return effectiveTheme === ThemeType.DARK;
  });

  // 监听系统主题变化
  useEffect(() => {
    if (currentTheme !== ThemeType.SYSTEM) return;

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

    // 初始化暗色模式状态
    setIsDarkMode(mediaQuery.matches);

    // 当系统主题变化时更新状态
    const handleChange = (e: MediaQueryListEvent) => {
      setIsDarkMode(e.matches);
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [currentTheme]);

  // 当主题改变时，保存到本地存储并更新文档根元素的data-theme属性
  useEffect(() => {
    localStorage.setItem('app-theme', currentTheme);

    const effectiveTheme = getEffectiveTheme(currentTheme);
    document.documentElement.setAttribute('data-theme', effectiveTheme);

    // 更新暗色模式状态
    setIsDarkMode(effectiveTheme === ThemeType.DARK);
  }, [currentTheme]);

  // 设置主题函数
  const setTheme = (theme: ThemeType) => {
    setCurrentTheme(theme);
  };

  // 上下文值
  const contextValue: ThemeContextType = {
    currentTheme,
    setTheme,
    isDarkMode,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      <ConfigProvider
        theme={{
          algorithm: isDarkMode ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
          token: {
            colorPrimary: '#409eff',
          },
        }}
      >
        {children}
      </ConfigProvider>
    </ThemeContext.Provider>
  );
};

// 使用主题Hook
export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

export default ThemeProvider;
